package com.zhhs.project.act.appactivity.controller;


import cn.hutool.jwt.JWTUtil;
import com.zhhs.common.core.redis.Redis;
import com.zhhs.common.core.redis.RedisCache;
import com.zhhs.common.utils.StringUtils;
import com.zhhs.framework.web.domain.AjaxResult;
import com.zhhs.project.act.activity.domian.ActActivityAdvanced;
import com.zhhs.project.act.activity.domian.ActUser;
import com.zhhs.project.act.activity.service.IActActivityAdvancedService;
import com.zhhs.project.act.activity.service.IActUserService;
import com.zhhs.project.act.appactivity.domian.AppUserVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: fenxiao
 * @description: 登录
 * @author: peng
 * @create: 2022-11-17 16:27
 **/
@Slf4j
@Controller
@RequestMapping("/wecom/mini-app")
public class AppLoginController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private IActUserService actUserService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IActActivityAdvancedService actActivityAdvancedService;
    @GetMapping("/getUserDetail")
    @ResponseBody
    public AjaxResult getUserDetail(Long userId){
       return AjaxResult.success(actUserService.selectActUserById(userId));
    }
    @PostMapping("/pushAddress")
    @ResponseBody
    public AjaxResult pushAddress(Long userId,String addressDetail,String city,String county,String province,String name,String phoneNumber,String areaCode){
        ActUser actUser = new ActUser();
        actUser.setId(userId);
        actUser.setAddressDetail(addressDetail);
        actUser.setCity(city);
        actUser.setCounty(county);
        actUser.setProvince(province);
        actUser.setName(name);
        actUser.setPhoneNumber(phoneNumber);
        actUser.setAreaCode(areaCode);
        actUser.setUpdateTime(new Date());

        int i = actUserService.updateActUser(actUser);
        if (i>0){
            return AjaxResult.success("成功");
        }else {
            return AjaxResult.success("失败");
        }

    }
    @GetMapping("/getEnjoyLink")
    @ResponseBody
    public AjaxResult getEnjoyLink(Long id){
        ActActivityAdvanced actActivityAdvanced= actActivityAdvancedService.selectEnjoyLink(id);
        return AjaxResult.success(actActivityAdvanced);
    }


    @PostMapping("/appLogin")
    @ResponseBody
    public AjaxResult appLogin(String code) {
        log.info("code:{}", code);
        if (StringUtils.isBlank(code)){
            return AjaxResult.error("请求CODE不能为空!");
        }
        try {
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
            String openid = userInfo.getOpenid();
            ActUser user = actUserService.selectActUserByOpenid(openid);
            if (user == null) {
                user = new ActUser();
                user.setOpenid(userInfo.getOpenid());
                user.setNickname(Base64.getEncoder().encodeToString(userInfo.getNickname().getBytes()));
                user.setProfile(userInfo.getHeadImgUrl());
                user.setUnionid(userInfo.getUnionId());
                user.setCreateTime(new Date());
                actUserService.insertActUser(user);
            } else {
                user.setNickname(userInfo.getNickname());
                user.setProfile(userInfo.getHeadImgUrl());
                actUserService.updateActUser(user);
            }
            String token = getToken(user);
            log.info("登录token:{}", token);
            String key = Redis.token.key(user.getId());
            redisCache.deleteObject(key);
            //保存token 24小时 每次登录会覆盖原来的token（自动登录有效时间）
            redisCache.setCacheObject(Redis.token.key(user.getId()), token);
            //返回用户信息
            AppUserVo appUserVo = new AppUserVo();
            appUserVo.setUserId(user.getId());
            appUserVo.setToken(token);
            return AjaxResult.success("登录成功",appUserVo);
        } catch (WxErrorException e) {
            return AjaxResult.error("授权失败,请稍后再试!");
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        byte[] decode = Base64.getDecoder().decode("5b+D5LmL5omA5ZCR");
        String s = new String(decode, "UTF-8");
        System.out.println(s);
    }
    public String getToken(ActUser user){
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("id", String.valueOf(user.getId()));
               // put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7);
            }
        };
        return  JWTUtil.createToken(map, user.getId().toString().getBytes());
    }
}
